package dao

import (
	"github.com/gin-gonic/gin"
	"time"
	"web_api_gin/dto"
	"web_api_gin/entity"
)

var SysOptLog = SysOptLogDao{}

type SysOptLogDao struct {
}

//获取日志列表
func (d *SysOptLogDao) GetList(ctx *gin.Context, searchParams *dto.SysOptLogGetListReq) ([]*entity.SysOptLog, int64, error) {
	var list []*entity.SysOptLog
	var total int64
	tx := DB(ctx).Model(&entity.SysOptLog{})
	if searchParams.UserId != 0 {
		tx = tx.Where("user_id = ?", searchParams.UserId)
	}
	if searchParams.UserName != "" {
		tx = tx.Where("user_name like ?", "%"+searchParams.UserName+"%")
	}
	if len(searchParams.PermId) > 0 {
		tx = tx.Where("perm_id = ?", searchParams.PermId[len(searchParams.PermId)-1])
	}
	if len(searchParams.TimeArea) > 0 {
		startTime, _ := time.ParseInLocation("2006-01-02 15:04:05", searchParams.TimeArea[0], time.Local)
		endTime, _ := time.ParseInLocation("2006-01-02 15:04:05", searchParams.TimeArea[len(searchParams.TimeArea)-1], time.Local)
		tx = tx.Where("add_time > ? AND add_time < ?", startTime.Unix(), endTime.Unix())
	}
	err := tx.Count(&total).Order("id DESC").Limit(int(searchParams.PageSize)).Offset(int((searchParams.PageNo - 1) * searchParams.PageSize)).Find(&list).Error
	for _, log := range list {
		log.AddTimeStr = time.Unix(log.AddTime, 0).Format("2006-01-02 15:04:05")
	}
	return list, total, err
}

// 保存日志
func (d *SysOptLogDao) SaveLog(ctx *gin.Context, data *entity.SysOptLog) error {
	return DB(ctx).Create(data).Error
}
